#include "widget.h"
#include "ui_widget.h"

#include <QMessageBox>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    // 给文本框设置相关模式
    ui->lineEdit_1->setEchoMode(QLineEdit::Password);
    ui->lineEdit_1->setClearButtonEnabled(true);

    ui->lineEdit_2->setEchoMode(QLineEdit::Password);
    ui->lineEdit_2->setClearButtonEnabled(true);
    ui->label_prompt->setText("密码为空");

    // 连接文本框的状态 与比较函数，用于实时传出两密码信息
    connect(ui->lineEdit_1, &QLineEdit::textEdited, this, &Widget::comparePwd);
    connect(ui->lineEdit_2, &QLineEdit::textEdited, this, &Widget::comparePwd);
}

Widget::~Widget()
{
    delete ui;
}

void Widget::comparePwd()
{
    // 比较两密码状态
    const QString& s1 = ui->lineEdit_1->text();
    const QString& s2 = ui->lineEdit_2->text();
    if(s1.isEmpty() && s2.isEmpty()){
        ui->label_prompt->setText("密码为空");
        ui->pushButton->setEnabled(false);
    }else if(s1 == s2){
        ui->label_prompt->setText("两次密码一致");
        ui->pushButton->setEnabled(true);
    }else{
        if (s1.isEmpty()) {
            ui->label_prompt->setText("第一个密码为空");
        } else if (s2.isEmpty()) {
            ui->label_prompt->setText("第二个密码为空");
        } else {
            ui->label_prompt->setText("两次密码不一致");
        }
        ui->pushButton->setEnabled(false);
    }
}


void Widget::on_pushButton_clicked()
{
    // 提取密码，弹出对话框显示密码
    QString Password =  ui->lineEdit_1->text();

    QMessageBox msgBox;
    msgBox.setText("您设置的密码为: " + Password);
    msgBox.exec();
}

// 两checkBox 用于显示两文本框中的密码
void Widget::togglePasswordVisibility()
{
    bool showPassword1 = ui->checkBox_1->isChecked();
    bool showPassword2 = ui->checkBox_2->isChecked();

    ui->lineEdit_1->setEchoMode(showPassword1 ? QLineEdit::Normal : QLineEdit::Password);
    ui->lineEdit_2->setEchoMode(showPassword2 ? QLineEdit::Normal : QLineEdit::Password);

    comparePwd(); // 每次切换密码可视化状态时重新比较密码
}


void Widget::on_checkBox_1_toggled(bool checked)
{
    togglePasswordVisibility();
}

void Widget::on_checkBox_2_toggled(bool checked)
{
    togglePasswordVisibility();
}

